﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Services.Client;
using TelerikStore.EbayService;
using Telerik.Web.UI;
using TelerikStore.MasterPages;
using System.Collections;
using System.Drawing;
using System.Xml;
using System.Net;

namespace TelerikStore.Views
{
    public partial class ProductList_ListView : System.Web.UI.UserControl
    {
        private static EBayData ebayContext;
        private static readonly String ebayString = "http://ebayodata.cloudapp.net";

        public List<ProductItem> Products
        {
            get
            {
                if (Session["Products"] == null)
                {
                    Session["Products"] = GetItemsList();
                }
                return (List<ProductItem>)Session["Products"];
            }
            set { Session["Products"] = value; }
        }

        //Public property to use with our CategoryID
        public String SearchText { get; set; }
        public String ListedCategoryId { get; set; }
        public String FilterQueryString { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            ebayContext = new EBayData(new Uri(ebayString));

            RadAjaxManager.GetCurrent(Page).AjaxSettings.AddAjaxSetting(ProductListView, Page.Master.Master.FindControl("CartRotator"));
            RadAjaxManager.GetCurrent(Page).AjaxSettings.AddAjaxSetting(ProductListView, Page.Master.Master.FindControl("ItemsTotalLabel"));
            RadAjaxManager.GetCurrent(Page).AjaxSettings.AddAjaxSetting(ProductListView, Page.Master.Master.FindControl("PriceTotalLabel"));
        }

        protected void ProductListView_ItemDrop(object sender, RadListViewItemDragDropEventArgs e)
        {
            AddItemToCart(e.DraggedItem.GetDataKeyValue("Id").ToString());
        }

        protected void ProductListView_ItemCommand(object sender, RadListViewCommandEventArgs e)
        {
            if (e.CommandName == "ProductClick")
            {
                ContentPlaceHolder leftPH = this.NamingContainer.NamingContainer.FindControl("LeftSideContent") as ContentPlaceHolder;
                RadListViewDataItem item = e.ListViewItem as RadListViewDataItem;
                RadMenu categoryMenu = this.NamingContainer.NamingContainer.FindControl("QuickCategoryMenu") as RadMenu;

                var id = item.GetDataKeyValue("Id");
                var productItem = Products.Single(p => p.Id == id.ToString());
                var minPrice = (leftPH.FindControl("StartRange") as RadNumericTextBox).Text;
                var maxPrice = (leftPH.FindControl("EndRange") as RadNumericTextBox).Text;
                var conditionId = (leftPH.FindControl("ConditionComboBox") as RadComboBox).SelectedValue;
                var searchTextBox = this.NamingContainer.FindControl("SearchBox") as RadTextBox;

                var redirectUrl = String.Format("./ProductView.aspx?Condition={0}&MinPrice={1}&MaxPrice={2}&ItemID={3}",
                    conditionId, minPrice, maxPrice, productItem.Id);

                if (!String.IsNullOrEmpty(searchTextBox.Text))
                    redirectUrl += "&Search=" + searchTextBox.Text;

                if (categoryMenu.SelectedItem != null)
                    redirectUrl += "&Category=" + categoryMenu.SelectedItem.Value;

                Products = null;
                Response.RedirectLocation = redirectUrl;
            }
            else if (e.CommandName == "AddToCart")
            {
                AddItemToCart(e.CommandArgument.ToString());
            }
        }

        protected void ProductListView_NeedDataSource(object sender, RadListViewNeedDataSourceEventArgs e)
        {
            ProductListView.DataSource = Products;
        }

        protected string ColorizePrice(RadListViewDataItem item)
        {
            ProductItem currentProduct = (ProductItem)item.DataItem;
            string coloredClassName;
            try
            {
                TimeSpan timeLeft = XmlConvert.ToTimeSpan(currentProduct.TimeLeft);
                string[] colors = new string[] { "red-price", "orange-price", "green-price" };

                //[Red]     lt 00:30:00
                //[Orange]  gte 00:30:00 && lt 12:00:00
                //[Green]   gt 12:00:00
                coloredClassName = timeLeft < new TimeSpan(0, 0, 30, 0) ? colors[0] :
                    timeLeft < new TimeSpan(0, 12, 0, 0) ? colors[1] : colors[2];
            }
            catch (FormatException)
            {
                coloredClassName = "brown-price";
            }

            return String.Format("<span class='price {0}'>{1:C}</span>", coloredClassName, currentProduct.Price);
        }

        private void AddItemToCart(string itemId)
        {
            Home HomeMaster = (Home)Page.Master.Master;
            ProductItem itemToBeAdded = Products.Find(pItem => pItem.Id == itemId);

            HomeMaster.AddItemToCart(itemToBeAdded);
        }

        private List<ProductItem> GetItemsList()
        {
            List<Item> itemsList = new List<Item>();
            List<ProductItem> listToReturn = new List<ProductItem>();

            string UriString = "Items?";

            if (!String.IsNullOrEmpty(ListedCategoryId) && !String.IsNullOrEmpty(SearchText))
            {
                UriString += String.Format("$filter=PrimaryCategoryId{3}{4}{0}{4}{2}{5}&search={1}", ListedCategoryId, SearchText, EbayQueryStringsHelper.And, EbayQueryStringsHelper.Equal, EbayQueryStringsHelper.Quote, FilterQueryString);
            }
            else if (!String.IsNullOrEmpty(ListedCategoryId))
            {
                UriString += String.Format("$filter=PrimaryCategoryId{2}{3}{0}{3}{1}{4}", ListedCategoryId, EbayQueryStringsHelper.And, EbayQueryStringsHelper.Equal, EbayQueryStringsHelper.Quote, FilterQueryString);
            }
            else
            {
                UriString += String.Format("$filter={1}&search={0}", SearchText, FilterQueryString);
            }

            try
            {
                itemsList = ebayContext.Execute<Item>(new Uri(UriString, UriKind.Relative)).ToList();
                foreach (Item item in itemsList)
                {
                    listToReturn.Add(new ProductItem(item));
                }

            }
            catch (Exception e)
            {
                if (e is WebException || e is ArgumentNullException || e is ArgumentException || e is InvalidOperationException)
                {
                    //suppress eBay-related exceptions
                }
                else
                {
                    throw;
                }
            }

            return listToReturn;
        }
    }
}
